package com.wyp168.juc.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @ClassName UnsafeDemo001
 * @Description TODO
 * @Author wyp168
 * @Date 2022/9/4 22:22
 */
public class UnsafeDemo001 {
    //获取一个Unsafe实例对象
//    static final Unsafe unsafe = Unsafe.getUnsafe();    //Caused by: java.lang.SecurityException: Unsafe 原因是Unsafe类必须使用BootStrap类加载器进行加载，而我们当前类使用的是APpClassLoader加载的，所以报错
    static final Unsafe unsafe;
    static final long stateOffset;

    private volatile long state = 0;

    static {
        try {
            //通过反射直接调用Unsafe的theUnsafe属性
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            //设置theUnsafe属性是可获取的
            field.setAccessible(true);
            //获取该变量的值
            unsafe = (Unsafe) field.get(null);

            //获取state变量在类UnsafeDemo001 中的偏移量
            stateOffset = unsafe.objectFieldOffset(UnsafeDemo001.class.getDeclaredField("state"));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            System.out.println(e.getLocalizedMessage());
            throw new Error(e);
        }
    }

    public static void main(String[] args) {
        //创建一个UnsafeDemo001 实例， 并设置state值
        UnsafeDemo001 test = new UnsafeDemo001();
        boolean isSuccess = unsafe.compareAndSwapInt(test, stateOffset, 0, 1);

        System.out.println(isSuccess);
        System.out.println("state: " + test.state);
    }
}
